<?php
// +----------------------------------------------------------------------
// | 基础类型服务层
// +----------------------------------------------------------------------
// | 主要服务于任务相关数据操作
// +----------------------------------------------------------------------
// | 错误编码头 201xxx
// +----------------------------------------------------------------------

namespace common\service;


use common\exception\LogicException;
use common\model\EntityModel;
use common\model\ProjectModel;
use common\model\TaskModel;
use support\ErrorCode;
use support\SingletonTrait;


class TaskDocumentService
{
    /** @var TaskModel */
    private $taskModel;

    // 单例工具
    use SingletonTrait;

    public function __construct()
    {
        $this->taskModel = model(TaskModel::class);
    }

    /**
     * 查询任务工序标准文档
     * @param $taskId
     * @return mixed|null
     * @throws \Exception
     */
    public function getTaskStepStandardDocument($taskId)
    {
        $taskData = $this->taskModel->find($taskId);
        if (empty($taskData)) {
            throw new LogicException('task not found', ErrorCode::TASK_NOT_FOUND);
        }
        $entityData = model(EntityModel::class)->field('step_workflow_id')->find($taskData['entity_id']);
        if (empty($entityData)) {
            throw new LogicException('entity not found', ErrorCode::ENTITY_NOT_FOUND);
        }
        $project = model(ProjectModel::class)->field('project_template_id')->find($taskData['project_id']);
        if (empty($project)) {
            throw new LogicException('project not found', ErrorCode::PROJECT_NOT_FOUND);
        }
        $attrStr = TaskService::getInstance()->getTaskStandardDocAttrStrById($taskId);
        return DocumentRelationService::getInstance()->findDocument(['param' => ['filter' => [
            'project_template_id' => $project['project_template_id'],
            'relation_type' => 'task_standard',
            'step_workflow_id' => $entityData['step_workflow_id'],
            'step_id' => $taskData['step_id'],
            'attr_str' => $attrStr,
        ]]]);
    }

}
